package com.leetcode.partition5;

import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2021/10/23 8:58
 */
public class LC492构造矩形 {

    public static int[] constructRectangle(int area) {
        int width = (int) Math.sqrt(area);
        while (area % width != 0) {
            width--;
        }
        return new int[]{area / width, width};
//        return doublePointer(area);
//        double edge = Math.sqrt(area);
//        //刚好能够完整开方，直接返回
//        if (Math.floor(edge + 0.5) == edge) {
//            return new int[]{(int) edge, (int) edge};
//        }
//        //不能完整开方，需要在原基础上长度加1，宽减一尝试
//        int length = (int) Math.ceil(edge), width = (int) Math.floor(edge);
//        return recursion(length, width, area);
    }

    public static void main(String[] args) {
//        System.out.println(Arrays.toString(constructRectangle(4)));
//        System.out.println(Arrays.toString(constructRectangle(28)));
        System.out.println(Arrays.toString(constructRectangle(122122)));
//        double n = 10.0;
//        System.out.println(Math.floor(Math.sqrt(n) + 0.5) == Math.sqrt(n));
    }

    private static int[] doublePointer(int area) {
        int edge = (int) Math.sqrt(area);
        int left = edge, right = edge;
        while (left <= right) {
            int curArea = left * right;
            if (curArea == area) return new int[]{right, left};
            if (curArea < area) right++;
            else left--;
        }
        return new int[]{area, 1};
    }

    private static int[] recursion(int length, int width, int area) {
        if (width <= 0 || length > area) return null;
        int curArea = length * width;
        if (curArea == area) {
            return new int[]{length, width};
        }
        int[] res = null;
        //当前面积小于指定面积，才能加长
        if (curArea < area) res = recursion(length + 1, width, area);
        //当前面积大于指定面积，才能减宽
        if (curArea > area) res = !check(res, area) ? recursion(length, width - 1, area) : res;

        res = !check(res, area) ? recursion(length + 1, width - 1, area) : res;
        return !check(res, area) ? new int[]{area, 1} : res;
    }

    private static boolean check(int[] res, int area) {
        if (res == null) return false;
        return res[0] != area;
    }
}
